package huixue.cn.com.rxapp.rx;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import huixue.cn.com.library.util.PixelUtils;

/**
 * Created by gongdongyang 2019/7/18
 * Describe:
 */
public class RecycleItemDecoration extends RecyclerView.ItemDecoration {
    private Paint mPaint;

    private int margin;

    public RecycleItemDecoration(int margin) {
        this.margin = PixelUtils.dp2px(margin);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        //mPaint.setStrokeWidth(PixelUtils.dp2px(margin));
        mPaint.setColor(Color.parseColor("#10000000"));
        //mPaint.setColor(Color.RED);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        //第一个ItemView不需要在上面绘制分割线
        if (parent.getChildAdapterPosition(view) != 0) {

            outRect.top = (int) margin;//指相对itemView顶部的偏移量
        }
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);

        int childCount = parent.getChildCount();
        //因为getItemOffsets是针对每一个ItemView，而onDraw方法是针对RecyclerView本身，所以需要循环遍历来设置
        for (int i = 0; i < childCount; i++) {
            View view = parent.getChildAt(i);
            int index = parent.getChildAdapterPosition(view);
            //第一个ItemView不需要绘制
            if (index == 0) {
                continue;//跳过本次循环体中尚未执行的语句，立即进行下一次的循环条件判断
            }
            float dividerTop = view.getTop() - margin;
            float dividerLeft = parent.getPaddingLeft() + 0;
            float dividerBottom = view.getTop();
            float dividerRight = parent.getWidth() - parent.getPaddingRight() - 0;
            c.drawRect(dividerLeft, dividerTop, dividerRight, dividerBottom, mPaint);
        }
    }


}
